package com.xinqi.common.base.utils.spring;

import org.springframework.aop.support.AopUtils;
import org.springframework.context.i18n.LocaleContext;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.format.datetime.standard.DateTimeContext;
import org.springframework.format.datetime.standard.DateTimeContextHolder;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.concurrent.CompletableFuture;

/**
 * @author linkai
 * @date 2023/5/2
 */
public interface Spring {
    static void committed(final Runnable action) {
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCommit() {
                    action.run();
                }
            });
        } else {
            action.run();
        }

    }

    static void committedAsync(final Runnable action) {
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void afterCommit() {
                    CompletableFuture.runAsync(() -> action.run());
                }
            });
        } else {
            action.run();
        }

    }

    static Class<?> getClass(Object o) {
        return AopUtils.getTargetClass(o);
    }

    static DateTimeContext getDateTimeContext() {
        return DateTimeContextHolder.getDateTimeContext();
    }

    static LocaleContext getLocaleContext() {
        return LocaleContextHolder.getLocaleContext();
    }
}
